<template>
	<view class="page-box">
		<!-- <scroll-view class="scroll-view" scroll-y scroll-with-animation :scroll-top="top"> -->
		<image src="../../static/message/chat-bg-2.png" class="bg-image"></image>
		<z-paging ref="paging" v-model="list" @query="getUserChatList" :use-page-scroll="true"
			:refresher-enabled="false" :auto="false" :auto-show-back-to-top="true" :loading-more-enabled="false">
			<view class="scroll-view">
				<view class="message" :class="[item.user_type === 1 ? 'self' : 'friend']" v-for="(item, index) in list"
					:key="index" @click="msgClick(item)">
					<view :class="[item.user_type === 1 ? 'message-item-self' : 'message-item-friend']">
						<!-- <image :src="item.avatar" v-if="item.user_type ！== 1" class="avatar" mode="widthFix"></image> -->
						<view v-if="item.user_type !== 1" class="friend_top">房东 {{ item.create_time_text }}</view>
						<view v-if="item.user_type === 1" class="self_top">{{ item.create_time_text }} 我</view>
						<!-- <image :src="item.avatar" v-if="item.user_type ！== 1" class="avatar" mode="widthFix"></image> -->
						<view class="content" v-if="item.images != ''">
							<u-image :src="item.images" :lazy-load="true" width="300rpx" height="200rpx" mode="widthFix"
								v-if="item.images != ''" @click="previewImage(item.images)"></u-image>
						</view>
						<view class="content" v-else>
							{{ item.content }}
						</view>

					</view>
				</view>
			</view>
			<view slot="bottom">
				<view class="tool">
					<block v-if="messageType === 'text'">
						<!-- <image src="../../static/voice.png" mode="widthFix" class="left-icon" @click="messageType='voice'"></image> -->
						<input type="text" v-model="content" class="input" @confirm="send" placeholder="请输入" style="margin-right: 0;" />
						<view
							style="padding: 10rpx 20rpx;background: #0095F8;color: #fff;border-radius: 10rpx;margin: 0 15rpx;"
							@click="send">发送</view>
						<image src="../../static/thumb2.png" mode="widthFix" class="thumb" @click="chooseImage"></image>
					</block>
					<!-- 	<block v-else-if="messageType === 'voice'">
						<image src="../../static/text.png" mode="widthFix" class="left-icon" @click="messageType='text'"></image>
						<text class="voice-crl" @touchstart="touchstart" @touchend="touchend">{{ recordStart ? '松开 发送' : '按住 说话' }}</text>
					</block> -->
				</view>
			</view>
		</z-paging>
		<!-- </scroll-view> -->


		<view v-if="recordStart" class="audio-animation">
			<view class="audio-wave">
				<text class="audio-wave-text" v-for="item in 10" :style="{ 'animation-delay': `${item / 10}s` }"></text>
				<view class="text">松开 发送</view>
			</view>
		</view>
	</view>
</template>

<script>
const recorderManager = wx.getRecorderManager()

export default {
	data() {
		return {
			content: '',
			list: [],
			top: 0,
			messageType: 'text', // text 发送文本；voice 发送语音
			recordStart: false,
			homeowner_id: null,
			chatInterVal: null,
		};
	},
	onLoad(options) {
		let that = this
		uni.setNavigationBarTitle({
			title: options.name
		})
		// this._friendAvatar = options.avatar
		// this._selfAvatar = 'https://ask.dcloud.net.cn/uploads/avatar/001/43/07/62_avatar_max.jpg?=1705916918'
		this.homeowner_id = options.user_id
		this.getOneUserChatList()
		//每3秒重新获取一次消息
		this.chatInterVal = setInterval(function () {
			that.getUserChatList()
		}, 3000)
	},
	onHide() {
		if (this._innerAudioContext) {
			this._innerAudioContext.stop()
		}
		if (this.chatInterVal) {
			clearInterval(this.chatInterVal)
			this.chatInterVal = null
		}
	},
	destroyed() {
		if (this.chatInterVal) {
			clearInterval(this.chatInterVal)
			this.chatInterVal = null
		}
	},
	methods: {
		previewImage(image) {
			uni.previewImage({
				urls: [image],
			});
		},
		getOneUserChatList() {
			this.$Api.chat.getUserChatList({
				homeowner_id: this.homeowner_id,
				page_size: 999999
			}).then(res => {
				this.$refs.paging.complete(res.data.data.data);
				setTimeout(() => {
					this.scrollToBottom()
				}, 500)
			})
		},
		getUserChatList(pageNo, pageSize) {
			this.$Api.chat.getUserChatList({
				homeowner_id: this.homeowner_id,
				page_size: 999999
			}).then(res => {
				this.$refs.paging.complete(res.data.data.data);
			})
		},
		send() {
			this.$Api.chat.postSendUserChat({
				homeowner_id: this.homeowner_id,
				content: this.content,
				images: ''
			}).then(res => {
				this.content = ''
				this.images = ''
				this.getUserChatList()
				setTimeout(() => {
					this.scrollToBottom()
				}, 500)
			})
		},
		chooseImage() {
			let that = this
			uni.chooseImage({
				// sourceType: 'album',
				count: 1,
				success: async (res) => {
					console.log(res)
					const tempFilePaths = res.tempFilePaths[0];
					let {
						fullurl
					} = await that.$uploadFilePromise(tempFilePaths)
					that.$Api.chat.postSendUserChat({
						homeowner_id: that.homeowner_id,
						content: '',
						images: fullurl
					}).then(res => {
						that.content = ''
						that.images = ''
						that.getUserChatList()
						setTimeout(() => {
							this.scrollToBottom()
						}, 500)
					})
				}
			})
		},
		scrollToBottom() {
			this.$refs.paging.scrollToBottom()
		},
		msgClick(data) {
			if (data.messageType === 'voice') {
				if (this._innerAudioContext) {
					this._innerAudioContext.stop()
					this._innerAudioContext.src = data.audioSrc
					this._innerAudioContext.play()
					return
				}
				this.play(data.audioSrc)
			}
		},

		authTips() {
			uni.showModal({
				title: '提示',
				content: '您拒绝了麦克风权限，将导致功能不能正常使用，去设置权限？',
				confirmText: '去设置',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.openSetting({
							success: (res) => {
								if (res.authSetting['scope.record']) {
									console.log("已授权麦克风");
									this._recordAuth = true
								} else {
									// 未授权
									wx.showModal({
										title: '提示',
										content: '您未授权麦克风，功能将无法使用',
										showCancel: false,
										confirmText: '知道了'
									})
								}
							}
						})
					}
				}
			})
		},

		touchstart() {
			//开始录音
			const _permission = 'scope.record'
			uni.getSetting({
				success: (res) => {
					// 判断是否有相关权限属性
					if (res.authSetting.hasOwnProperty(_permission)) {
						// 属性存在，且为false，用户拒绝过权限
						if (!res.authSetting[_permission]) {
							this.authTips()
						} else {
							// 已授权
							this._recordAuth = true
							// 开始录音
							recorderManager.start()
							recorderManager.onStart(() => {
								this.recordStart = true
							})

							// 错误回调
							recorderManager.onError((res) => {
								console.log('recorder error', res)
								uni.showToast({
									icon: 'none',
									title: '系统出错，请重试'
								})
								this.recordStart = false
							})
						}
					} else {
						// 属性不存在，需要授权
						uni.authorize({
							scope: _permission,
							success: () => {
								// 授权成功
								this._recordAuth = true
							},
							fail: (res) => {
								/**
								 * 104 未授权隐私协议
								 * 用户可能拒绝官方隐私授权弹窗，为了避免过度弹窗打扰用户，开发者再次调用隐私相关接口时，
								 * 若距上次用户拒绝不足10秒，将不再触发弹窗，直接给到开发者用户拒绝隐私授权弹窗的报错
								 */
								if (res.errno == 104) {
									uni.showModal({
										title: '温馨提示',
										content: '您拒绝了隐私协议，请稍后再试',
										confirmText: '知道了',
										showCancel: false,
										success: () => { }
									})
								} else {
									// 用户拒绝授权
									this.authTips()
								}
							}
						})
					}
				}
			})
		},

		touchend() {
			if (!this._recordAuth || !this.recordStart) return
			//停止录音
			recorderManager.stop();
			recorderManager.onStop((res) => {
				console.log('结束录音', res)
				const {
					duration,
					tempFilePath
				} = res
				this.recordStart = false

				this.list.push({
					content: `语音 ${Math.round(duration / 1000)}''`,
					audioSrc: tempFilePath,
					user_type: 1,
					avatar: this._selfAvatar,
					messageType: 'voice'
				})
				this.scrollToBottom()
			})
		},

		//播放声音
		play(src) {
			this._innerAudioContext = wx.createInnerAudioContext()
			this._innerAudioContext.src = src
			this._innerAudioContext.play()
			this._innerAudioContext.onPlay(() => {
				console.log('开始播放')
			})
			this._innerAudioContext.onEnded(() => {
				// 播放完毕，清除音频链接
				console.log('播放完毕');
			})
			this._innerAudioContext.onError((res) => {
				console.log('audio play error', res)
			})
		},
	}
}
</script>
<style lang="scss" scoped>
.page-box {
	background: #DDEEFD;
	min-height: 100vh;
	position: relative;

	.bg-image {
		position: fixed;
		top: 0;
		width: 100%;
		height: 400rpx;
		z-index: 10;
	}
}

.scroll-view {
	position: relative;
	z-index: 100;
	padding: 30rpx 30rpx;
	box-sizing: border-box;
}

.message {
	display: flex;
	align-items: flex-start;
	margin-bottom: 30rpx;

	.message-item-friend {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.message-item-self {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.self_top {
		font-size: 26rpx;
		color: #999999;
		line-height: 36rpx;
		text-align: right;
		margin-bottom: 20rpx;
	}

	.friend_top {
		font-size: 26rpx;
		color: #999999;
		line-height: 36rpx;
		text-align: left;
		margin-bottom: 20rpx;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 10rpx;
		margin-right: 30rpx;
	}

	.content {
		min-height: 80rpx;
		max-width: 60vw;
		box-sizing: border-box;
		font-size: 28rpx;
		line-height: 1.3;
		padding: 20rpx;
		border-radius: 10rpx;

		.image {
			width: 300rpx;
			height: auto;
		}
	}

	&.self {
		justify-content: flex-end;

		.avatar {
			margin: 0 0 0 30rpx;
		}

		.content {
			position: relative;
			background: #0095F8;
			color: #ffffff;

			// &::after {
			// 	position: absolute;
			// 	content: '';
			// 	width: 0;
			// 	height: 0;
			// 	border: 16rpx solid transparent;
			// 	border-left: 16rpx solid #FE4F04;
			// 	right: -28rpx;
			// 	top: 24rpx;
			// }
		}
	}

	&.friend {
		.content {
			position: relative;
			background: rgba(255, 255, 255, 0.65);
			// &::after {
			// 	position: absolute;
			// 	content: '';
			// 	width: 0;
			// 	height: 0;
			// 	border: 16rpx solid transparent;
			// 	border-right: 16rpx solid #fff;
			// 	left: -28rpx;
			// 	top: 24rpx;
			// }
		}
	}
}

.tool {
	width: 100%;
	min-height: 120rpx;
	background: #fff;
	display: flex;
	align-items: center;
	box-sizing: border-box;
	padding: 20rpx 24rpx 20rpx 40rpx;
	padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)/2) !important;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom)/2) !important;

	.left-icon {
		width: 56rpx;
		height: 56rpx;
		margin-right: 10rpx;
	}

	.input,
	.voice-crl {
		background: #eee;
		border-radius: 10rpx;
		height: 70rpx;
		margin-right: 30rpx;
		flex: 1;
		padding: 0 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	.thumb {
		width: 64rpx;
		height: 64rpx;
	}

	.voice-crl {
		text-align: center;
		line-height: 70rpx;
		font-weight: bold;
	}
}

.audio-animation {
	position: fixed;
	// width: 100vw;
	// height: 100vh;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	z-index: 202410;
	display: flex;
	justify-content: center;
	align-items: center;

	.text {
		text-align: center;
		font-size: 28rpx;
		color: #333;
		margin-top: 60rpx;
	}

	.audio-wave {
		padding: 50rpx;

		.audio-wave-text {
			background-color: blue;
			width: 7rpx;
			height: 12rpx;
			margin: 0 6rpx;
			border-radius: 5rpx;
			display: inline-block;
			border: none;
			animation: wave 0.25s ease-in-out;
			animation-iteration-count: infinite;
			animation-direction: alternate;
		}

		/*  声波动画  */
		@keyframes wave {
			from {
				transform: scaleY(1);
			}

			to {
				transform: scaleY(4);
			}
		}
	}
}
</style>